package com.taomu.app.zongchouhuli.moudle.mine.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.permissions.RxPermissions;
import com.taomu.app.zongchouhuli.R;
import com.taomu.app.zongchouhuli.framework.BaseActivity;
import com.taomu.app.zongchouhuli.http.res.ResChoiceRechargeEntity;
import com.taomu.app.zongchouhuli.http.res.ResRechargeEntity;
import com.taomu.app.zongchouhuli.moudle.mine.adpter.RechargePayWayAdp;
import com.taomu.app.zongchouhuli.moudle.mine.adpter.SelectMoneyAdp;
import com.taomu.app.zongchouhuli.moudle.mine.contract.UserCashContract;
import com.taomu.app.zongchouhuli.moudle.mine.contract.UserRechargeContract;
import com.taomu.app.zongchouhuli.moudle.mine.contract.impl.UserRechargePresenter;
import com.taomu.app.zongchouhuli.moudle.mine.entity.PayWayEntity;
import com.taomu.app.zongchouhuli.utils.FileUtils;
import com.taomu.app.zongchouhuli.utils.zxing.QrUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

public class UserRechargeActivity extends BaseActivity<UserRechargeContract.Presenter> implements UserRechargeContract.View {

    private ImageView mBackIm;

    private TextView mPriceTv;

    private TextView mOrderNumTv;

    private RecyclerView mPayWayRecy;

    private RechargePayWayAdp mAdp;

    private TextView mCompanyTv;

    private TextView mCopyCompanyTv;

    private TextView mWechatTv;

    private TextView mWechatCopyTv;

    private TextView mSubmitTv;

    private LinearLayout mWechatPayLin;

    private LinearLayout mOtherPayLin;

    private ImageView mCodeIm;

    private TextView mRechargeTypeTv;

    private RecyclerView mRechargeRecy;

    private SelectMoneyAdp mSelectAdp;

    private TextView mBankTv;

    private TextView mCopyBankTv;

    private LinearLayout mBankLin;

    private EditText mInputEditTv;

    private TextView mRechargeTipTv;

    private String[] moneys = {"100","500","1000","5000","10000","20000"};

    private List<String> moneyList = new ArrayList<>();

    private LinearLayout mAlipayTipLin;

    private ImageView mAlipayCodeIm;

    private LinearLayout mShopTipLin;

    private ImageView mShopCodeIm;

    @Override
    protected void onDestroy() {
        mPresenter.onDetch();
        super.onDestroy();
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initView() {
        mAlipayTipLin = findViewById(R.id.recharge_alipay_code_lin);
        mAlipayCodeIm = findViewById(R.id.recharge_alipay_code_im);
        mShopTipLin = findViewById(R.id.recharge_shop_code_lin);
        mShopCodeIm = findViewById(R.id.recharge_shop_code_im);
        mRechargeTipTv = findViewById(R.id.recharge_tip_tv);
        mRechargeTipTv.setText(alipaytip);
        mBackIm = findViewById(R.id.recharge_back_im);
        mPriceTv = findViewById(R.id.recharge_price_tv);
        mOrderNumTv = findViewById(R.id.recharge_order_num);
        mBankTv = findViewById(R.id.recharge_bank_tv);
        mCopyBankTv = findViewById(R.id.recharge_copy_bank_tv);
        mBankLin = findViewById(R.id.bank_lin);
        mAdp = new RechargePayWayAdp(this);
        mPayWayRecy = findViewById(R.id.recharge_type_recy);
        mPayWayRecy.setLayoutManager(new LinearLayoutManager(this));
        mPayWayRecy.setAdapter(mAdp);
        mCompanyTv = findViewById(R.id.recharge_company_tv);
        mCopyCompanyTv = findViewById(R.id.recharge_copy_company_tv);
        mWechatTv = findViewById(R.id.recharge_wechat_tv);
        mWechatCopyTv = findViewById(R.id.recharge_copy_wechat_tv);
        mSubmitTv = findViewById(R.id.recharge_submit_tv);
        mWechatPayLin = findViewById(R.id.recharge_wechat_code_lin);
        mOtherPayLin = findViewById(R.id.recharge_otherpay_lin);
        mCodeIm = findViewById(R.id.recharge_wechat_code_im);
        mRechargeTypeTv = findViewById(R.id.recharge_type_tv);
        mSelectAdp = new SelectMoneyAdp(this);
        mRechargeRecy = findViewById(R.id.select_money_recy);
        mRechargeRecy.setAdapter(mSelectAdp);
        mRechargeRecy.setLayoutManager(new GridLayoutManager(this, 3));
        mInputEditTv = findViewById(R.id.input_type_et);
    }

    private String tip1 = "支付宝账号已经复制到剪贴板";

    private String tip2 = "收款人已经复制到剪贴板";

    private String alipaytip = "1.请先查看入款账号信息\n" +
            "2.支付成功后请点击下一步\n" +
            "3.如出现充值失败或充值未到账等情况.请联系在线客服获取帮助";

    private String wechattip = "1.请先查看入款收款图或账号信息\n" +
            "2.截图保存或长按图片两秒自动保存到手机相册\n" +
            "3.扫码支付成功后请点击下一步\n" +
            "4.如出现充值失败或者充值未到账等情况，请联系在线客服获取帮助";

    private String banktip = "1.请先查看入款账号信息\n" +
            "2.支付成功后请点击下一步\n" +
            "3.如出现充值失败或充值未到账等情况.请联系在线客服";

    private String alipaycodetip = "1.请先查看入款收款图或账号信息\n" +
            "2.截图保存或长按图片两秒自动保存到手机相册\n" +
            "3.扫码支付成功后请点击下一步\n" +
            "4.如出现充值失败或充值未到账等情况.请联系在线客服获取帮助";

    private String shopcodetip = "1.请先查看入款收款图或账号信息\n" +
            "2.截图保存或长按图片两秒自动保存到手机相册\n" +
            "3.扫码支付成功后请点击下一步\n" +
            "4.如出现充值失败或充值未到账等情况.请联系在线客服获取帮助";

    @Override
    protected void initData() {
        for(int i=0;i<moneys.length;i++){
            moneyList.add(moneys[i]);
        }
        mSelectAdp.setData(moneyList);
        mPresenter.getPayWayData();
        mPresenter.getRechargeInfo();
    }

    @Override
    protected void initEvent() {
        mSubmitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mAdp.getSelect() == null){
                    showToast("请选择支付方式");
                }else{
                    if(!TextUtils.isEmpty(mInputEditTv.getText().toString())) {
                        //修改之后直接跳转到订单界面
                        mPresenter.getSubmit(mInputEditTv.getText().toString(), currentStatus);
                    }else{
                        showToast("请输入或选择支付金额");
                    }
                }
            }
        });
        mCopyCompanyTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                copy(mCompanyTv.getText().toString(),"复制成功");
            }
        });
        mWechatCopyTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                copy(mWechatTv.getText().toString(),"复制成功");
            }
        });
        mCopyBankTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                copy(mBankTv.getText().toString(), "复制成功");
            }
        });
        mBackIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mAdp.setRechargePayWayListener(new RechargePayWayAdp.RechargePayWayListener() {
            @Override
            public void onItemClick(PayWayEntity entity) {
                if(entity.getTitle().contains("商户充值")){
                    mRechargeTipTv.setText(shopcodetip);
                    mAlipayTipLin.setVisibility(View.GONE);
                    mShopTipLin.setVisibility(View.VISIBLE);
                    mWechatPayLin.setVisibility(View.GONE);
                    mOtherPayLin.setVisibility(View.GONE);
                    mRechargeTypeTv.setText("商户:");
                    mWechatTv.setText("64217998123");
                    currentStatus = "charge_alipay_shop";
                }else if(entity.getTitle().contains("支付宝扫码支付")){
                    mRechargeTipTv.setText(alipaycodetip);
                    mAlipayTipLin.setVisibility(View.VISIBLE);
                    mShopTipLin.setVisibility(View.GONE);
                    mWechatPayLin.setVisibility(View.GONE);
                    mOtherPayLin.setVisibility(View.GONE);
                    mRechargeTypeTv.setText("支付宝二维码:");
                    mWechatTv.setText("64217998123");
                    currentStatus = "charge_alipay_scan";
                }else if(entity.getTitle().contains("微信")){
                    mRechargeTipTv.setText(wechattip);
                    mAlipayTipLin.setVisibility(View.GONE);
                    mShopTipLin.setVisibility(View.GONE);
                    mWechatPayLin.setVisibility(View.VISIBLE);
                    mOtherPayLin.setVisibility(View.GONE);
                    mRechargeTypeTv.setText("微信号:");
                    mWechatTv.setText("64217998123");
                    currentStatus = "charge_wechat";
                }else if(entity.getTitle().contains("支付宝充值")){
                    mRechargeTipTv.setText(alipaytip);
                    mWechatPayLin.setVisibility(View.GONE);
                    mAlipayTipLin.setVisibility(View.GONE);
                    mShopTipLin.setVisibility(View.GONE);
                    mOtherPayLin.setVisibility(View.VISIBLE);
                    mBankLin.setVisibility(View.GONE);
                    mRechargeTypeTv.setText("支付宝账号:");
                    mCompanyTv.setText(alipayNum);
                    mWechatTv.setText(alipayAccount);
                    currentStatus = "charge_alipay";
                }else if(entity.getTitle().contains("银联")){
                    mWechatPayLin.setVisibility(View.GONE);
                    mBankLin.setVisibility(View.VISIBLE);
                    mAlipayTipLin.setVisibility(View.GONE);
                    mShopTipLin.setVisibility(View.GONE);
                    mRechargeTipTv.setText(banktip);
                    mOtherPayLin.setVisibility(View.VISIBLE);
                    mRechargeTypeTv.setText("银联卡号:");
                    mCompanyTv.setText(bankNum);
                    mWechatTv.setText(bankAccount);
                    mBankTv.setText(bankName);
                    currentStatus = "charge_unionpay";
                }
            }
        });
        mSelectAdp.setSelectMoneyListener(new SelectMoneyAdp.SelectMoneyListener() {
            @Override
            public void onItemClick(String money) {
                mInputEditTv.setText(money);
            }
        });
        mCodeIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBaseDialog(wechatImg);
            }
        });
        mCodeIm.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                saveBitmap(mCodeIm.getDrawable());
                return true;
            }
        });
        mAlipayCodeIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBaseDialog(alipcodeImg);
            }
        });
        mAlipayCodeIm.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                saveBitmap(mAlipayCodeIm.getDrawable());
                return true;
            }
        });
        mShopCodeIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBaseDialog(shopcodeImg);
            }
        });
        mShopCodeIm.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                saveBitmap(mShopCodeIm.getDrawable());
                return true;
            }
        });
    }

    private void saveBitmap(final Drawable drawabl){
        RxPermissions rx = new RxPermissions(this);
        rx.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if(aBoolean){
                            if(drawabl != null){
                                BitmapDrawable bd = (BitmapDrawable) drawabl;
                                Bitmap bm = bd.getBitmap();
                                if(bm != null){
                                    String filePath = com.taomu.app.zongchouhuli.utils.FileUtils.saveToSystemGallery(UserRechargeActivity.this, bm);
                                    showToast(filePath);
                                }else{
                                    showToast("保存图片失败");
                                }
                            }else{
                                showToast("保存图片失败");
                            }

                        }else{
                            showToast("保存图片需要先允许相关权限");
                        }
                    }
                });
    }

    private Dialog dialog;

    private void showBaseDialog(String msg){
        if(dialog == null) {
            View view = LayoutInflater.from(UserRechargeActivity.this).inflate(R.layout.dialog_show_qr, null);
            dialog = new Dialog(UserRechargeActivity.this);
            ImageView view1 = view.findViewById(R.id.dialog_code_im);
            Glide.with(UserRechargeActivity.this).load(msg).into(view1);
            view1.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if(currentStatus.equals("charge_alipay_shop")){
                        saveBitmap(mShopCodeIm.getDrawable());
                    }else if(currentStatus.equals("charge_alipay_scan")){
                        saveBitmap(mAlipayCodeIm.getDrawable());
                    }else if(currentStatus.equals("charge_wechat")){
                        saveBitmap(mCodeIm.getDrawable());
                    }
                    return true;
                }
            });
            dialog.setContentView(view);
            dialog.show();
        }else{
            dialog.show();
        }
    }

    private String wechatImg = "";

    private String alipayNum = "";

    private String alipayAccount = "";

    private String bankNum = "";

    private String bankAccount = "";

    private String currentStatus = "charge_alipay_shop";
    //charge_wechat、charge_unionpay、charge_alipay
    @Override
    protected UserRechargeContract.Presenter createPresenter() {
        return new UserRechargePresenter(this);
    }

    @Override
    public void setPayWayData(List<PayWayEntity> mData) {
        mAdp.setData(mData);
    }

    private String alipcodeImg;

    private String shopcodeImg;

    @Override
    public void setPayWayInfo(ResChoiceRechargeEntity mData) {
        if(mData.getInfo() != null){
            if(mData.getInfo().getCharge_alipay_scan() != null){
                if(mData.getInfo().getCharge_alipay_scan().size()>0){
                    alipcodeImg = mData.getInfo().getCharge_alipay_scan().get(0).getValue();
                    Glide.with(this).load(alipcodeImg).into(mAlipayCodeIm);
                }
            }
            if(mData.getInfo().getCharge_alipay_shop() != null){
                if(mData.getInfo().getCharge_alipay_shop().size()>0){
                    shopcodeImg = mData.getInfo().getCharge_alipay_shop().get(0).getValue();
                    Glide.with(this).load(shopcodeImg).into(mShopCodeIm);
                }
            }
            if(mData.getInfo().getCharge_wechat() != null){
                if(mData.getInfo().getCharge_wechat().size()>0){
                    wechatImg = mData.getInfo().getCharge_wechat().get(0).getValue();
                    Glide.with(this).load(wechatImg).into(mCodeIm);
                }
            }
            if(mData.getInfo().getCharge_alipay() != null){
                if(mData.getInfo().getCharge_alipay().size()>=2){
                    alipayNum = mData.getInfo().getCharge_alipay().get(0).getValue();
                    alipayAccount = mData.getInfo().getCharge_alipay().get(1).getValue();
                    mCompanyTv.setText(alipayAccount);
                    mWechatTv.setText(alipayNum);
                }
            }
            if(mData.getInfo().getCharge_unionpay() != null){
                if(mData.getInfo().getCharge_unionpay().size()>=2){
                    bankNum = mData.getInfo().getCharge_unionpay().get(0).getValue();
                    bankAccount = mData.getInfo().getCharge_unionpay().get(1).getValue();
                }
                if(mData.getInfo().getCharge_unionpay().size()>=3){
                    bankName = mData.getInfo().getCharge_unionpay().get(2).getValue();
                }
            }

        }
    }

    private String bankName = "";

    @Override
    public void setSubmit(ResRechargeEntity data) {
        UserConfirmRechargeActivity.start(this, data.getProduct_id(), String.valueOf(data.getOrder_id()), data.getTotal_price(),  String.valueOf(data.getOrder_id()));
        finish();
    }

    private void copy(String copystr, String msg){
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", copystr);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        showToast(msg);
    }

    @Override
    public void setPresenter(UserRechargeContract.Presenter presenter) {

    }
}
